package br.com.agenda.controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import br.com.agenda.entity.Cliente;
import br.com.agenda.service.ClienteService;

@Controller
@RequestMapping(value = "/agendaController")
public class AgendaController {

	// get log4j handler
	private static final Logger logger = Logger
			.getLogger(AgendaController.class);

	@Autowired
	private ClienteService clienteService;

	@Autowired
	private ClienteValidator validator;

	@RequestMapping(value = "listar", method = RequestMethod.GET)
	public ModelAndView listaCliente() {

		logger.debug("Metodo listar chamado");

		List<Cliente> clientes = clienteService.buscarTodosClientes();

		System.out.println(clientes);

		return new ModelAndView("listaClientes", "clientes", clientes);

	}

	@RequestMapping(value = "adicionarCliente", method = RequestMethod.GET)
	public ModelAndView preparaAdicionarCliente() {

		logger.debug("Metodo adicionarCliente chamado");

		Cliente cliente = new Cliente();

		return new ModelAndView("addCliente", "cliente", cliente);

	}

	@RequestMapping(value = "adicionarCliente", method = RequestMethod.POST)
	public ModelAndView adicionarCliente(
			@ModelAttribute("cliente") Cliente cliente, BindingResult result) {

		logger.debug("Metodo adicionarCliente chamado");

		validator.validate(cliente, result);
		if (result.hasErrors()) {
			return new ModelAndView("addCliente");
		}

		this.clienteService.salvar(cliente);

		return new ModelAndView("listaClientes");

	}

}
